package com.marvels.approve.loan.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.Page;
import com.marvels.approve.loan.dto.DownInfoConditionDto;
import com.marvels.approve.loan.dto.DownListConditionDto;
import com.marvels.approve.loan.dto.ListQueryConditionDto;
import com.marvels.approve.loan.dto.LoanDetailDto;
import com.marvels.approve.loan.service.LoanListService;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.MarvelsLogUtil;

/**
 * 放款处理
 * 
 * @author tangpw
 *
 */
@RestController
@RequestMapping("approve/loanList/service")
public class LoanListController {

	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	
	@Autowired
	private LoanListService listQueryService;

	
	/**
	 * 查询清单
	 * @param listQueryConditionDto
	 * @return
	 */
	@RequestMapping("listQuery")
	@ResponseBody
	public MarvelsResultDTO listQuery(@RequestBody ListQueryConditionDto listQueryConditionDto) {
		MarvelsLogUtil.getInstance().info("/finance/loanHandle/listQuery>>>>>>>>>>>>" + listQueryConditionDto);
		try {
			Page<LoanDetailDto> list = listQueryService.queryLoanList(listQueryConditionDto);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
					list);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>放款处理清单查询FAIL:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), null);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>放款处理清单查询异常:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(),
					null);
		}

	}

	/**
	 * list的筛选条件
	 * @param listQueryConditionDto
	 * @return
	 */
	@RequestMapping("listScreenCondition")
	@ResponseBody
	public MarvelsResultDTO listScreenCondition() {
		try {
			Map<String, Object> map = new HashMap<>();
			map = listQueryService.listScreenCondition();
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
					map);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>清单查询list的筛选FAIL:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>清单查询list的筛选条件:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(),
					null);
		}

	}

	
	
	/**
	 * 基础数据list的筛选条件
	 * @param listQueryConditionDto
	 * @return
	 */
	@RequestMapping("baseCondition")
	@ResponseBody
	public MarvelsResultDTO baseCondition() {
		try {
			Map<String, Object> map = new HashMap<>();
			map = listQueryService.baseCondition();
			return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
					map);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>查询基础数据list的筛选条件FAIL:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), MarvelsErrorCode.FAIL.getDesc(), null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>查询基础数据list的筛选条件失败:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(),
					null);
		}

	}
	
	
	@RequestMapping("downLoadBatch")
	public void downLoadBatch(@RequestParam(value="loanIds") String ids, HttpServletRequest request, HttpServletResponse response) {
		String desc = "批量下载-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		try {
			byte[] batchByte = listQueryService.downLoadBatch("", ids, "", "");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-download;charset=utf-8");// 设置response内容的类型
			if (batchByte.length > 0) {
				response.setHeader("Content-disposition",
						"attachment;filename=" + new String((desc + ".zip").getBytes(), "ISO8859-1"));// 设置头部信息
				OutputStream outs = response.getOutputStream();// 获取文件输出IO流
				BufferedOutputStream bouts = new BufferedOutputStream(outs);
				bouts.write(batchByte);
				bouts.flush();// 这里一定要调用flush()方法
				bouts.close();
				outs.close();
				MarvelsLogUtil.getInstance().info(desc + "批量文件下载成功");
			} else {
				response.setHeader("Content-disposition", "attachment;filename=信息未找到.txt");
				response.getWriter().print(desc + "未找到数据，请确认！");
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>批量下载出错了！", e);
			response.setHeader("Content-disposition", "attachment;filename=信息未找到.txt");
			try {
				response.getWriter().print("批量下载异常！");
			} catch (IOException e1) {
				MarvelsLogUtil.getInstance().error("批量下载异常", e);
			}
		}
	}

	/**
	 * 查询下载资料信息下载任务总条数总金额详情
	 * @param downListInfoConditionDto
	 * @return
	 */
	@RequestMapping("downListDetail")
	@ResponseBody
	public MarvelsResultDTO downListDetail(@RequestBody DownListConditionDto downListInfoConditionDto) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = listQueryService.downList(downListInfoConditionDto);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>查询下载资料信息下载任务总条数,总金额异常:", e);
			return MarvelsResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), MarvelsErrorCode.ERROR.getDesc(),
					null);
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
				result);
	}

	/**
	 * 清单下载
	 * @param downListInfoConditionDto
	 * @return
	 */
	@RequestMapping("downList")
	public void downList(DownInfoConditionDto downListConditionDto, HttpServletRequest request,
			HttpServletResponse response) {
		String desc = "清单下载-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		byte[] data = null;
		try {
			data = listQueryService.downLoadBatch(downListConditionDto.getFund(), downListConditionDto.getLoanIdsList(), "",
					"");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-download;charset=utf-8");
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String((desc + ".zip").getBytes(), "ISO8859-1"));// 设置头部信息
			OutputStream outputStream = response.getOutputStream();
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
			bufferedOutputStream.write(data);
			bufferedOutputStream.flush();
			bufferedOutputStream.close();
			outputStream.close();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>清单下载异常:", e);
			response.setHeader("Content-disposition", "attachment;filename=信息未找到.txt");
			try {
				response.getWriter().print("清单下载异常！");
			} catch (IOException e1) {
				MarvelsLogUtil.getInstance().error("清单下载异常:", e);
			}
		}
	}

	/**
	 * 重签合同
	 * @return
	 */
	@RequestMapping("resignContract")
	@ResponseBody
	public MarvelsResultDTO resignContract(@RequestBody String loanIds) {
		List<String> loanIdList = Arrays.asList(loanIds.substring(1, loanIds.length() - 1).split(","));
		if (loanIdList != null && loanIdList.size() > 0) {
			for (String loanId : loanIdList) {
				try {
					// 重签合同逻辑

				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error(">>>>>>重签合同," + "进件单号：" + loanId, e);
					return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), "进件单号：" + loanId + "签署失败",
							null);
				}
			}
		} else {
			return MarvelsResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(), "请选择需要重签的选项", null);
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
				null);
	}
}
